package com.lhn.controller;

import com.lhn.entity.Admin;
import com.lhn.entity.User;
import com.lhn.feign.AccountFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @author lhn
 * @date 2024-10-13 13:25
 */

@Controller
@RequestMapping("consumer/account/")
public class AccountController {

    @Autowired
    private AccountFeign accountFeign;

    @PostMapping("login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("type") String type,
            HttpSession session
    ) {
        System.out.println(username + " " + password + " " + type);
        switch (type) {
            case "admin":
                Admin admin = new Admin();
                admin.setUsername(username);
                admin.setPassword(password);
                Admin admin1 = accountFeign.login(admin);
                System.out.println("admin1 is " + admin1);
                if ( admin1 != null) {
                    session.setAttribute("admin", admin);
                    return "main";
                } else {
                    return "login";
                }

            case "user":
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                User user1 = accountFeign.login(user);
                if ( user1!= null) {
                    session.setAttribute("user", user1);
                    return "index";
                } else {
                    return "login";
                }

            default:
                return "error";
        }
    }

    @GetMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate();   // 销毁session
        return "redirect:/login.html";
    }
}
